#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define CODE_LENGTH 6
#define NAME_LENGTH 8

typedef struct {
    char code[CODE_LENGTH];
    int score;
    char name[NAME_LENGTH];
    int name_length;
} student;

void print_student(student[], int);
void swap_element(student[], int, int);
int compare_element_code(const void *, const void *);
int compare_element_name(const void *, const void *);
int compare_element_score(const void *, const void *);

int main()
{
    int num, order_code, case_num = 0;
    while (scanf("%d %d", &num, &order_code) != EOF) {
        if (num == 0) 
            break;

        student *student_list = (student *)malloc(sizeof(student) * num);
        for (int i = 0; i < num; i++) {
            scanf("%s %s %d", student_list[i].code, 
                student_list[i].name, &student_list[i].score);
            student_list[i].name_length = strlen(student_list[i].name);
        }

        switch (order_code) {
            case 1:
                qsort(student_list, num, sizeof(student), compare_element_code);
                break;
            case 2:
                qsort(student_list, num, sizeof(student), compare_element_name);
                break;
            case 3:
                qsort(student_list, num, sizeof(student), compare_element_score);
                break;
        }

        printf("Case %d:\n", ++case_num);
        print_student(student_list, num);
    }
}

void print_student(student array[], int num)
{
    for (int i = 0; i < num; i++) {
        // printf(">> ");
        for (int j = 0; j < CODE_LENGTH; j++)
            printf("%c", array[i].code[j]);
        printf(" ");
        for (int j = 0; j < array[i].name_length; j++)
            printf("%c", array[i].name[j]);
        // printf(" %s", array[i].name);
        printf(" %d\n", array[i].score);
    }
}

int compare_element_code(const void *i, const void *j)
{
    const student *a = i;
    const student *b = j;
    int a_code = atoi(a->code);
    int b_code = atoi(b->code);

    if (a_code == b_code)
        return 0;
    else if (a_code > b_code)
        return 1;
    else
        return -1;
}

int compare_element_score(const void *i, const void *j)
{
    const student *a = i;
    const student *b = j;

    if (a->score != b->score) {
        if (a->score > b->score)
            return 1;
        else
            return -1;
    } else {
        return compare_element_code(i, j);
    }
}

int compare_element_name(const void *i, const void *j)
{
    const student *a = i;
    const student *b = j;

    if (strcmp(a->name, b->name) != 0)
        return strcmp(a->name, b->name);
    else
        return compare_element_code(i, j);
}
